package leetcode.N601_N700;


public class N622 {

    public static void main(String[] args) {
        MyCircularQueue m = new MyCircularQueue(2);
        m.enQueue(4);
        m.Rear();
        m.enQueue(9);
        m.deQueue();
        m.Front();
        m.deQueue();
        m.deQueue();
        m.isEmpty();
        m.deQueue();
        m.enQueue(6);
        m.enQueue(4);
    }
}


class MyCircularQueue {

    int [] elements;
    int head;
    int tail;
    int size;
    boolean isFerrule;

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        this.size = k;
        this.head = 0;
        this.tail = 0;
        this.isFerrule = false;
        this.elements = new int[size];
    }

    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        elements[tail] = value;
        tail = nextTail();
        return true;
    }

    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        head = nextHead();
        return true;
    }

    /** Get the front item from the queue. */
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        return elements[head];
    }

    /** Get the last item from the queue. */
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        return elements[lastTail()];
    }

    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return !isFerrule && head == tail;
    }

    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        return isFerrule && head == tail;
    }

    private int nextHead() {
        if (head == size - 1) {
            isFerrule = false;
            return 0;
        }
        return head + 1;
    }

    private int nextTail() {
        if (tail == size - 1) {
            isFerrule = true;
            return 0;
        }
        return tail + 1;
    }

    private int lastTail() {
        return tail == 0 ? size - 1 : tail - 1;
    }
}